;(function() {
    var $form_add_task = $('.add-task')
        , $body = $('body')
        , task_list = {}
        , $delete_task_trigger
        , $detial_task_trigger
        , $task_detial_mask = $('.task-detial-mask')
        , $task_detial = $('.task-detial')
        , current_index
        , $update_form
        , $task_detial_content
        , $task_detial_content_input
        , $checkbox_complete
        , $msg = $('.msg')
        , $msg_content = $msg.find('.msg-content')
        , $msg_confirm = $msg.find('.anchor.confirmed')
        , $alerter = $('.alerter');
        ;
    init();
    
    //点击添加按钮
    $form_add_task.on('submit', function(e) {
        var new_task = {};
        e.preventDefault(); //禁用默认行为
        new_task.content = $(this).find('input[name=content]').val();//获取新task的值
        if(!new_task.content) return;
        //存入新的task
        if(add_task(new_task)) {
            //render_task_list();
            $(this).find('input[name=content]').val(null);
        }
    });

    //查找并监听所有按钮的点击事件
    function listen_task_delete() {
        $delete_task_trigger.on('click', function() {
            //找到删除链接所在的task元素
            var $item = $(this).parent().parent();
            var index = $item.data('index');
            var tmp = confirm('确定删除');
            tmp ? delete_task(index) : null;
        });
    }

    //监听 详情按钮
    function listen_task_detial() {
        $('.task-item').on('dblclick',function() {
            var index = $(this).data('index');
            show_task_detial(index);
        })

        $detial_task_trigger.on('click', function() {
            var $item = $(this).parent().parent();
            var index = $item.data('index');
            show_task_detial(index);
        })
    }

    /**监听完成task事件 */
    function listen_checkbox_complete() {
        $checkbox_complete.on('click', function() {
            //var is_complete = $(this).is(':checked');
            var index = $(this).parent().parent().data('index');
            var item = store.get('task_list')[index];
            if(item.complete) {
                update_task(index, {complete: false});
            } else {
                update_task(index, {complete: true});
            }
        })
    }

    /**
     * 
     */
     function listen_msg_event() {
         $msg_confirm.on('click',function() {
             hide_msg();
         })
     }

    //点击遮掩层 隐藏详情悬浮框
    $task_detial_mask.on('click', hide_task_detail);

    //新增
    function add_task(new_task) {
        task_list.push(new_task); //将新的task推入 task_list
        //store.set('task_list',task_list);  
        //更新localStorage
        refresh_task_list();
        return true;
    }
    
    //删除一条task
    function delete_task(index) {
        //如果没有index或index不存在
        if(index === undefined || !task_list[index]) return;
        delete task_list[index];
        refresh_task_list();
    }


    //显示一条task
    function show_task_detial(index) {
        render_task_detial(index);
        current_index = index;
        $task_detial.show();
        $task_detial_mask.show();
    }

    function update_task(index, data) {
        if(index === undefined || !task_list[index]) return;
        //{complete: true/flase}
        task_list[index] = $.extend({}, task_list[index], data);
        //task_list[index] = data;
        refresh_task_list();
        //console.log('task_list[index]',task_list[index]);
    }

    //隐藏详情
    function hide_task_detail() {
        $task_detial.hide();
        $task_detial_mask.hide();
    }

    //更新LocalStorage,并渲染模板
    function refresh_task_list() {
        store.set('task_list',task_list);
        render_task_list();
    }

     //渲染所有的task
    function render_task_list() {
        var $task_list = $('.task-list'); //选中列表div
        $task_list.html(''); 
        var complete_item = [];
        for(var i=0; i<task_list.length; i++) {
            var item = task_list[i];
            if(item && item.complete)
                complete_item[i] = item;
            else
                var $task = render_task_item(task_list[i],i);
             $task_list.prepend($task); 
        } 
        console.log(complete_item);
        for(var j=0; j<complete_item.length; j++) {
            var $task = render_task_item(complete_item[j],j);
            if(!$task) continue;
            $task.addClass('completed');
            $task_list.append($task);  
        }
        $delete_task_trigger = $('.action.delete');
        $detial_task_trigger = $('.action.detial');
        $checkbox_complete = $('.task-list .complete');
        listen_task_delete();
        listen_task_detial();
        listen_checkbox_complete();
    }

    //渲染单条task模板
    function render_task_item(data,index) {
        if(!data || !index) return;
        var list_item_tpl = 
        '<div class="task-item" data-index="'+index+'">' +
        '<span><input class="complete"'+ (data.complete ? 'checked' : '')+ ' type="checkbox"></span>' +
        '<span class="task-content">'+data.content+'</span>' + 
        '<span class="fr">'+ 
        '<span class="action delete"> 删除</span>' + 
        '<span class="action detial"> 详细</span>' +
        '</span>'+
        '</div>';
        return $(list_item_tpl);
    }

    //渲染指定task详情信息
    function render_task_detial(index) {
        if(index === undefined || !task_list[index]) return;
        var item = task_list[index];
        var tpl = '<form>' +
                '<div class="content">'+item.content+'</div>' +
                '<div class="input-item"><input type="text" style="display:none;" name="content" value="'+ item.content +'"/></div>'+
                '<div>' +
                '<div class="desc input-item"><textarea name="desc" id="" cols="30" rows="10">'+(item.desc || '')+'</textarea></div>' +
                '</div>' +
                '<div class="remind input-item">' +
                '<label>提醒时间</label>' + 
                '<input type="text" id="datetimepicker" name="remind_date" value="'+ (item.remind_date || '') +'">' +
                '</div>' + 
                '<div class="input-item"><button type="submit">更新</button></div>' +
                '</form>';
        $task_detial.html(null);
        $task_detial.html(tpl);
        $('#datetimepicker').datetimepicker();
        $update_form = $task_detial.find('form');
        $task_detial_content = $update_form.find('.content');
        $task_detial_content_input = $update_form.find('[name=content]');
        $task_detial_content.on('dblclick',function() {
            $task_detial_content_input.show();
            $task_detial_content.hide();
        })
        
        $update_form.on('submit',function(e) {
            e.preventDefault();
            var data = {};
            data.content = $(this).find('[name=content]').val();
            data.desc = $(this).find('[name=desc]').val();
            data.remind_date = $(this).find('[name=remind_date]').val();
            update_task(index , data);
            hide_task_detail();
        })

    }

    function init() {
        //store.clear();
        task_list = store.get('task_list') || [];
        listen_msg_event();
        if(task_list.length) {
            render_task_list();
            task_remind_check();
        }
    }


    function task_remind_check() {
        var current_timestamp;
        var itl = setInterval(function() {
            for(var i=0; i<task_list.length; i++) {
                var item = store.get('task_list')[i] , task_timestamp;
                // console.log('item',item);
                if(!item || !item.remind_date || item.informed)
                    continue;

                current_timestamp = (new Date()).getTime();
                task_timestamp = (new Date(item.remind_date)).getTime();
                console.log('current_timestamp,task_timestamp',current_timestamp,task_timestamp);
                if(current_timestamp - task_timestamp >= 1) {
                    console.log(0)
                    update_task(i,{informed: true});//添加一个字段，已经提醒过了
                    show_msg(item.content);
                }
            }
        },300);
        
    }

    function show_msg(msg) {
        if(!msg) return;
        $msg_content.html(msg);
        $alerter.get(0).play();
        $msg.show();
    }

    function hide_msg() {
        $msg.hide();
    }

    /**
     * 自定义alert
     */
    function pop(arg) {
        if(!arg) {
            console.error('pop title is required');
        }
        var conf = {}, $box, $mask;
        $box = $('<div>hello world</div>').css({width: 600, height: 300, background: '#fff'}); 
        if(typeof arg == 'string') {
            conf.title = arg;
        } else {
            conf = $.extend(conf,arg);
        }
        console.log('conf',conf);  
        $body.append($box);
    }
})();